from flask import render_template, g, current_app, jsonify, request

from info import constants, db
from info.models import News, Comment, CommentLike
from info.response_code import RET
from info.utils.common import get_user_info
from . import news_bp


@news_bp.route('/comment_like',methods=['POST'])
@get_user_info
def comment_like():
    #　１　获取参数　 1.1 comment_id:评论id， user:当前登录的用户对象， action:点赞&取消点赞的行为
    user=g.user
    comment_id = request.json.get('comment_id')
    action = request.json.get('action')
    # 2  参数校验
    if not all ([comment_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    if action not in ["add", "remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 3 逻辑处理
    # 根据　comment_id 查询 comment 对象
    try:
       comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询评论对象异常")
    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="评论对象不存在，不能点赞")
    # *　查询comment_like 对象
    try:
        # 用户确定，评论确定＞＞
        comment_like = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                     CommentLike.user_id == user.id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询收藏对象异常")
    if action == "add":
        if not comment_like :
            comment_like_obj = CommentLike()
            comment_like_obj.comment_id = comment_id
            comment_like_obj.user_id = user.id
            comment.like_count += 1
            db.session.add(comment_like_obj)
    else:
        if comment_like:
            db.session.delete(comment_like)
            comment.like_count -= 1
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存评论点赞对象异常")
            # 4 返回值
    return jsonify(errno=RET.OK, errmsg="OK")




@news_bp.route('/news_comment',methods=['POST'])
@get_user_info
def news_comment():
    # 1获取参数  news_id:新闻id，user:当前登录的用户，
    #   comment:评论的内容，parent_id:区分主评论和子评论字段【非必传】
    user = g.user
    news_id = request.json.get('news_id')
    content = request.json.get("comment")
    parent_id = request.json.get("parent_id")
    # 2 参数校验
    if not all ([news_id,content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 3 逻辑处理
    try:
       news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻对象异常")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻不存在不能发布评论")
    # 创建评论对象
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news.id
    comment.content = content
    if parent_id:
        comment.parent_id = parent_id
    try:
       db.session.add(comment)
       db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存评论对象异常")
    # 返回值  前端需要局部刷训评论 所以返回评论给前端
    comment_dict=comment.to_dict() if comment else None
    data={
        'comment':comment_dict
    }
    return jsonify(errno=RET.OK, errmsg="OK",data=data)


@news_bp.route('/news_collect',methods=['POST'])
@get_user_info
def news_collect():
    # 1-获取参数
    #   news_id: 当前新闻id值， action: 收藏 & 取消收藏的行为， user: 当前登录的用户
    news_id=request.json.get('news_id')
    action = request.json.get("action")
    user = g.user
    # 2-校验参数
    if not all ([news_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    if action not in  ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 3-逻辑处理
    # 判断新闻对象
    try:
       news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻对象异常")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻对象不存在")
    # 根据action 判断 行为
    if action == 'collect':
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存新闻收藏数据异常")
    return jsonify(errno=RET.OK, errmsg="OK")


@news_bp.route('/<int:news_id>')
@get_user_info
def news_detail(news_id):
    user=g.user
    user_dict = user.to_dict() if user else None
    # ------点击排行数据查询-------------
    try:
        # 得到查询到的新闻对象列表
        news_rank_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询点击排行新闻对象异常")
    # 将得到的向新闻对象列表数据 转换成 字典列表数据
    newsrank_dict_list=[]
    for new in news_rank_list if news_rank_list else []:
        newsrank_dict_list.append(new.to_dict())
    #-----------查询新闻详细数据 ---------------------
    try:
       news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻数据异常")
    news_detail_dict=news.to_dict() if news else None
    #-------------查询当前用户是否收藏该新闻-------------
    is_collected = False
    if user:
        if news in user.collection_news:
            is_collected = True
    #------------查询当前新闻对应的评论列表数据----------
    comment_list = []
    try:
       comment_list=Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询评论对象异常")
    # ----------------6.查询当前登录用户具体对那几条评论点赞-----------
    comment_id_list = [comment.id for comment in comment_list]
    commentlike_id_list = []
    if user:
        try:
            commentlike_list = CommentLike.query.filter(CommentLike.comment_id.in_(comment_id_list),
                                                        CommentLike.user_id == user.id).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")
        commentlike_id_list = [commentlike_obj.comment_id for commentlike_obj in commentlike_list]

    comment_dict_list=[]
    # 评论对象转字典
    for comment in comment_list if comment_list else []:
        comment_dict = comment.to_dict()
        comment_dict['is_like'] = False
        if comment.id in commentlike_id_list:
            comment_dict['is_like'] = True
        comment_dict_list.append(comment_dict)

    # ------------组织返回数据------------------------
    data={
        "user_info": user_dict,
        "click_news_list": newsrank_dict_list,
        'news':news_detail_dict,
        'is_collected':is_collected,
        'comment':comment_dict_list
    }
    return render_template("news/detail.html",data=data)


